import { render, h, shallowReactive } from "vue";
import type { CreateMessage, instance } from "./type";
import useZindex from "@/hooks/useZindex";
import MessageVue from "./Message.vue";
//创建一个数组存储每个message的信息
let messageArr: instance[] = shallowReactive([]);
let send = 1;

//创建一个渲染函数用于渲染组件
export const createMessage = (props: CreateMessage) => {
  const { changeZindex } = useZindex()
  //创建message数组id
  const id = `message--${send++}`;
  //准备一个节点
  const container = document.createElement("div");
  //封装一个方法，将message组件销毁
  const destroy = () => {
    //删除数组中对应的信息
    const idx = messageArr.findIndex((item) => item.id == id);
    if (idx == -1) return;
    messageArr.splice(idx, 1);
    render(null, container);
  };
  //删除一个message组件
  const ondestory = ()=>{
    let idx = messageArr.findIndex((item) => item.id == id);
    if (idx == -1) return;
    messageArr[idx].vm.exposed!.isShow.value = false;
  }
  //将remove方法挂载到props上
  const newProps = {
    ...props,
    id,
    zIndex:changeZindex(),
    Ondestroy: destroy,
  };
  //创建vnode
  const vnode = h(MessageVue, newProps);

  //渲染组件
  render(vnode, container);

  //将渲染好的组件插入文档  !在ts中为非空断言操作符 意味着不为空或者undefind
  document.body.appendChild(container.firstElementChild!);
  let vm = vnode.component!;
  let instance: instance = {
    id,
    vm,
    VNode: vnode,
    props: newProps,
    ondestory:ondestory
  };
  messageArr.push(instance);
  return instance;
};
//获取最后一个messge信息
export const messageLast = () => {
  return messageArr[messageArr.length - 1];
};
//获取消息的偏移量
export const getOffset = (id: string) => {
  let idx = messageArr.findIndex((item) => item.props.id == id);
//   console.log("idx", id, idx, messageArr.length);

  if (idx <= 0) {
    return 0;
  } else {
    let pre = messageArr[idx - 1];
    // console.log(pre.vm.exposed);

    return pre.vm.exposed?.bottomOffset.value;
  }
};
//全部关闭
export const closeAll = () => {
  for(let i = 0;i<messageArr.length;i++) {
    messageArr[i].ondestory();
  }
}
